//
// Created by ZLY on 2025/5/11.
//

#include "text_label.h"

TextLabel *TextLabel::addTextLabelChild(ObjectScreen *parent, const std::string &text, const std::string &font_path,
                                        int font_size, Anchor anchor) {
    auto label = new TextLabel();
    label->init();
    label->setParent(parent);
    label->setFont(font_path, font_size);
    label->setTTFText(text);
    label->setAnchor(anchor);
    label->updateSize();
    if (parent) {
        parent->addChild(label);
    }
    return label;
}


void TextLabel::render() {
    ObjectAffiliate::render();
    auto pos = parent_->getRenderPos() + offset_;
    TTF_DrawRendererText(ttf_text_, pos.x, pos.y);
}

void TextLabel::clean() {
    ObjectAffiliate::clean();
    if (ttf_text_) {
        TTF_DestroyText(ttf_text_);
    }
}

void TextLabel::setFont(const std::string &font_path, int font_size) {
    font_path_ = font_path;
    font_size_ = font_size;
    auto font = game_.getResourceStore()->getFont(font_path_, font_size_);
    if (!ttf_text_) {
        ttf_text_ = game_.createTTF_Text("", font_path_, font_size_);
    }
    TTF_SetTextFont(ttf_text_, font);
    updateSize();
}

void TextLabel::setFontPath(std::string font_path) {
    font_path_ = font_path;
    auto font = game_.getResourceStore()->getFont(font_path_, font_size_);
    TTF_SetTextFont(ttf_text_, font);
    updateSize();
}

void TextLabel::setFontSize(int font_size) {
    font_size_ = font_size;
    auto font = game_.getResourceStore()->getFont(font_path_, font_size_);
    TTF_SetTextFont(ttf_text_, font);
    updateSize();
}

void TextLabel::setTTFText(std::string text) const {
    TTF_SetTextString(ttf_text_, text.c_str(), 0);
}

void TextLabel::updateSize() {
    int w, h;
    TTF_GetTextSize(ttf_text_, &w, &h);
    setSize(glm::vec2(w, h));
}
